#!/usr/bin/env node

/**
 * 国际化扫描工具 - 仅扫描和分析，不进行翻译和替换
 * 用于检测项目中需要国际化但尚未国际化的中文文本
 */

const fs = require('fs');
const path = require('path');

class I18nScanner {
  constructor() {
    this.projectRoot = path.resolve(__dirname, '../');
    this.srcPath = path.join(this.projectRoot, 'src');
    
    // 改进的中文正则表达式
    this.chineseRegex = /[\u4e00-\u9fa5][\u4e00-\u9fa5\s\.,，。！？；：()（）""\''']*[\u4e00-\u9fa5]/g;
    this.singleChineseRegex = /[\u4e00-\u9fa5]/g;
    
    // 需要扫描的文件扩展名
    this.fileExtensions = ['.vue', '.js', '.ts'];
    
    // 排除的目录
    this.excludeDirs = ['node_modules', '.git', 'dist', 'build', 'i18n', 'uni_modules'];
    
    // 新发现的中文文本
    this.foundChineseTexts = new Map();
    
    console.log('🔍 国际化扫描工具启动');
    console.log(`📁 项目根目录: ${this.projectRoot}`);
  }

  run() {
    console.log('\n🔍 开始扫描项目中的中文文本...');
    
    this.scanDirectory(this.srcPath);
    
    console.log(`\n🎯 扫描完成！发现 ${this.foundChineseTexts.size} 个需要国际化的中文文本\n`);
    
    this.generateDetailedReport();
  }

  scanDirectory(dirPath) {
    const files = fs.readdirSync(dirPath);
    
    files.forEach(file => {
      const filePath = path.join(dirPath, file);
      const stat = fs.statSync(filePath);
      
      if (stat.isDirectory()) {
        if (!this.excludeDirs.includes(file)) {
          this.scanDirectory(filePath);
        }
      } else {
        const ext = path.extname(file);
        if (this.fileExtensions.includes(ext)) {
          this.scanFile(filePath);
        }
      }
    });
  }

  scanFile(filePath) {
    try {
      const content = fs.readFileSync(filePath, 'utf8');
      const lines = content.split('\n');
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        if (!line) continue;
        
        // 存储已处理的字符位置，避免重复匹配
        const processedPositions = new Set();
        
        // 多字符中文匹配 - 优先处理
        const chineseMatches = line.match(this.chineseRegex);
        if (chineseMatches) {
          chineseMatches.forEach(match => {
            const cleanMatch = match.trim();
            if (cleanMatch.length > 1 && this.shouldTranslate(line, cleanMatch)) {
              this.addFoundText(cleanMatch, filePath, i + 1, line);
              
              // 记录已处理的字符位置
              const matchIndex = line.indexOf(match);
              if (matchIndex !== -1) {
                for (let j = matchIndex; j < matchIndex + match.length; j++) {
                  processedPositions.add(j);
                }
              }
            }
          });
        }
        
        // 单个中文字符匹配（在引号内，且未被多字符匹配处理）
        const singleChineseMatches = line.match(this.singleChineseRegex);
        if (singleChineseMatches) {
          let searchStartIndex = 0;
          singleChineseMatches.forEach(match => {
            const charIndex = line.indexOf(match, searchStartIndex);
            searchStartIndex = charIndex + 1;
            
            // 只处理未被多字符匹配覆盖的单个字符
            if (!processedPositions.has(charIndex) && 
                this.isSingleChineseInQuotes(line, match) && 
                this.shouldTranslate(line, match)) {
              this.addFoundText(match, filePath, i + 1, line);
            }
          });
        }
      }
      
    } catch (error) {
      console.warn(`⚠️ 无法读取文件 ${filePath}:`, error.message);
    }
  }

  addFoundText(text, filePath, lineNumber, lineContent) {
    if (!this.foundChineseTexts.has(text)) {
      this.foundChineseTexts.set(text, {
        locations: [],
        count: 0
      });
    }
    
    const textInfo = this.foundChineseTexts.get(text);
    textInfo.locations.push({
      file: filePath,
      line: lineNumber,
      content: lineContent.trim()
    });
    textInfo.count++;
  }

  shouldTranslate(line, chineseText) {
    // 清理文本
    const cleanText = chineseText.trim().replace(/^[，。！？；：（）【】""\'''、\s]+|[，。！？；：（）【】""\'''、\s]+$/g, '');
    
    if (!cleanText || cleanText.length === 0) return false;
    
    // 跳过已经国际化的文本
    if (line.includes('$t(') || line.includes('this.$t(')) return false;
    
    // 跳过console语句
    if (this.isConsoleStatement(line)) return false;
    
    // 跳过注释
    if (this.isCommentLine(line)) return false;
    
    // 跳过URL和路径
    if (line.includes('http') || line.includes('://') || line.includes('/static/') || line.includes('./')) return false;
    
    // 跳过import/require语句
    if (line.includes('import') || line.includes('require(') || line.includes('export')) return false;
    
    // 跳过技术术语
    const technicalTerms = ['vue', 'js', 'css', 'html', 'json', 'md', 'scss', 'ts', 'node_modules', 'dist', 'build'];
    if (technicalTerms.includes(cleanText.toLowerCase())) return false;
    
    // 跳过纯标点符号
    if (cleanText.length === 1 && /[，。！？；：（）【】""\'''、\s\.,;:()[\]{}]/.test(cleanText)) return false;
    
    // 跳过数字字母组合
    if (/^[a-zA-Z0-9\-_]+$/.test(cleanText)) return false;
    
    // 必须包含中文字符
    if (!/[\u4e00-\u9fa5]/.test(cleanText)) return false;
    
    // 检查是否是用户界面文本
    if (this.isUserFacingText(line, chineseText)) return true;
    
    // 长度检查
    if (cleanText.length < 1) return false;
    
    return true;
  }

  isUserFacingText(line, chineseText) {
    const uiPatterns = [
      /title\s*[:=]/i,
      /placeholder\s*[:=]/i,
      /label\s*[:=]/i,
      /message\s*[:=]/i,
      /text\s*[:=]/i,
      /<text[^>]*>/i,
      /<button[^>]*>/i,
      /showToast/i,
      /showModal/i,
      /confirm/i,
      /alert/i,
      /\.toast\(/i,
      /\.modal\(/i
    ];
    
    return uiPatterns.some(pattern => pattern.test(line));
  }

  isSingleChineseInQuotes(line, chineseChar) {
    const charIndex = line.indexOf(chineseChar);
    if (charIndex === -1) return false;
    
    // 检查单引号
    const singleQuoteBefore = line.lastIndexOf("'", charIndex);
    const singleQuoteAfter = line.indexOf("'", charIndex + 1);
    if (singleQuoteBefore !== -1 && singleQuoteAfter !== -1) return true;
    
    // 检查双引号
    const doubleQuoteBefore = line.lastIndexOf('"', charIndex);
    const doubleQuoteAfter = line.indexOf('"', charIndex + 1);
    if (doubleQuoteBefore !== -1 && doubleQuoteAfter !== -1) return true;
    
    // 检查模板字符串
    const backtickBefore = line.lastIndexOf('`', charIndex);
    const backtickAfter = line.indexOf('`', charIndex + 1);
    if (backtickBefore !== -1 && backtickAfter !== -1) return true;
    
    return false;
  }

  isCommentLine(line) {
    if (line.startsWith('//') || line.startsWith('*') || line.startsWith('/*')) return true;
    if (line.startsWith('<!--') || line.includes('<!--') || line.includes('-->')) return true;
    return false;
  }

  isConsoleStatement(line) {
    return line.includes('console.') || 
           line.includes('console[') ||
           line.includes('console.log') ||
           line.includes('console.warn') ||
           line.includes('console.error') ||
           line.includes('console.info') ||
           line.includes('console.debug');
  }

  generateDetailedReport() {
    console.log('📊 详细扫描报告:');
    console.log('='.repeat(80));
    
    // 按出现频次排序
    const sortedTexts = Array.from(this.foundChineseTexts.entries())
      .sort((a, b) => b[1].count - a[1].count);
    
    // 按文件分组统计
    const fileStats = new Map();
    for (const [text, info] of this.foundChineseTexts) {
      for (const location of info.locations) {
        const relativeFile = path.relative(this.projectRoot, location.file);
        if (!fileStats.has(relativeFile)) {
          fileStats.set(relativeFile, 0);
        }
        fileStats.set(relativeFile, fileStats.get(relativeFile) + 1);
      }
    }
    
    console.log(`\n📁 文件统计 (Top 10):`);
    const sortedFiles = Array.from(fileStats.entries()).sort((a, b) => b[1] - a[1]).slice(0, 10);
    sortedFiles.forEach(([file, count]) => {
      console.log(`   ${file}: ${count} 个文本`);
    });
    
    console.log(`\n📝 高频中文文本 (Top 20):`);
    sortedTexts.slice(0, 20).forEach(([text, info]) => {
      console.log(`   "${text}" (出现 ${info.count} 次)`);
      
      // 显示前3个位置
      info.locations.slice(0, 3).forEach(location => {
        const relativeFile = path.relative(this.projectRoot, location.file);
        console.log(`     - ${relativeFile}:${location.line}`);
      });
      
      if (info.locations.length > 3) {
        console.log(`     - ... 还有 ${info.locations.length - 3} 个位置`);
      }
      console.log('');
    });
    
    if (sortedTexts.length > 20) {
      console.log(`   ... 还有 ${sortedTexts.length - 20} 个中文文本未显示`);
    }
    
    console.log('\n🔍 按文件类型统计:');
    const typeStats = new Map();
    for (const [text, info] of this.foundChineseTexts) {
      for (const location of info.locations) {
        const ext = path.extname(location.file);
        if (!typeStats.has(ext)) {
          typeStats.set(ext, 0);
        }
        typeStats.set(ext, typeStats.get(ext) + 1);
      }
    }
    
    for (const [ext, count] of typeStats) {
      console.log(`   ${ext} 文件: ${count} 个文本`);
    }
    
    console.log('\n💡 建议:');
    console.log('   1. 优先处理高频出现的文本');
    console.log('   2. 按文件逐个处理，避免遗漏');
    console.log('   3. 对于UI相关的文本要特别注意国际化');
    console.log('   4. 可以使用 scripts/i18n-auto-fixed.js 进行自动化处理');
    
    console.log('\n='.repeat(80));
  }
}

// 运行扫描
if (require.main === module) {
  const scanner = new I18nScanner();
  scanner.run();
}

module.exports = I18nScanner;